import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Input, Button, Select, Card, Tabs, Spin, message, List, Typography, Space, Collapse, Divider, TimePicker } from 'antd';
import { CarOutlined, CompassOutlined, ClockCircleOutlined, QuestionOutlined, ReloadOutlined } from '@ant-design/icons';
import { RoutePlan, RouteOptimizationType, Customer, RoutePoint, Location } from '../types';
import { getAllCustomers } from '../services/customerService';
import { optimizeRoute } from '../services/routeService';
import MapComponent from '../components/MapComponent';
import dayjs from 'dayjs';
import { TRANSPORT_MODES } from '../components/common';

const { Option } = Select;
const { TabPane } = Tabs;
const { Panel } = Collapse;
const { Title, Text } = Typography;

const OptimizeRoute: React.FC = () => {
  // 状态定义
  const [currentAddress, setCurrentAddress] = useState<string>('');
  const [selectedCustomers, setSelectedCustomers] = useState<Customer[]>([]);
  const [optimizationType, setOptimizationType] = useState<RouteOptimizationType>(
    RouteOptimizationType.SHORTEST_DISTANCE
  );
  const [customerCount, setCustomerCount] = useState<number>(3); // 默认拜访3个客户
  const [transportMode, setTransportMode] = useState<'driving' | 'walking' | 'bicycling' | 'transit'>('driving');
  const [loading, setLoading] = useState<boolean>(false);
  const [routePlans, setRoutePlans] = useState<RoutePlan[]>([]);
  const [selectedRouteIndex, setSelectedRouteIndex] = useState<number>(0);
  const [mapMarkers, setMapMarkers] = useState<any[]>([]);
  const [mapPolylines, setMapPolylines] = useState<any[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loadingCustomers, setLoadingCustomers] = useState<boolean>(true);
  const [mapKey, setMapKey] = useState<number>(0);
  const [startDate, setStartDate] = useState<dayjs.Dayjs>(dayjs());
  const [startTime, setStartTime] = useState<dayjs.Dayjs>(dayjs().hour(9).minute(0)); // 默认9:00开始
  const [endTime, setEndTime] = useState<dayjs.Dayjs>(dayjs().hour(17).minute(0)); // 默认17:00结束
  const [nearbyCustomers, setNearbyCustomers] = useState<Customer[]>([]);
  const [currentLocation, setCurrentLocation] = useState<{longitude: number; latitude: number} | null>(null);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [mapCenter, setMapCenter] = useState<[number, number]>([121.47, 31.23]); // 默认上海中心位置
  const [loadingNearby, setLoadingNearby] = useState<boolean>(false);
  // 添加一个刷新状态来强制重新渲染
  const [refreshKey, setRefreshKey] = useState<number>(0);

  // 获取地址的经纬度坐标
  const getLocationCoordinates = async (address: string) => {
    try {
      setLoading(true);
      const key = '4449ac26963227ad33708de521f024c5'; // 高德地图Web服务API的key
      const apiUrl = `https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${encodeURIComponent(address)}`;
      const response = await fetch(apiUrl);
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
      }
      const data = await response.json();
      if (data.status === '1' && data.geocodes && data.geocodes.length > 0) {
        const location = data.geocodes[0].location;
        const [lng, lat] = location.split(',').map(Number);
        setCurrentLocation({ longitude: lng, latitude: lat });
        setMapCenter([lng, lat]);
        return { longitude: lng, latitude: lat };
      } else {
        message.error(`无法获取地址坐标: ${data.info || '未知错误'}`);
        return null;
      }
    } catch (error) {
      message.error(`获取坐标时发生错误: ${error instanceof Error ? error.message : '未知错误'}`);
      return null;
    } finally {
      setLoading(false);
    }
  };

  // 计算两点之间的距离（使用Haversine公式）
  const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
    const R = 6371; // 地球半径，单位公里
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
      Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c; // 返回距离，单位公里
  };

  const getCustomerCoordinates = (customer: Customer): { longitude: number; latitude: number } | null => {
    if (!customer.location) {
      return null;
    }
    try {
      if (typeof customer.location === 'string') {
        const parts = (customer.location as string).split(',');
        if (parts.length === 2) {
          const longitude = parseFloat(parts[0]);
          const latitude = parseFloat(parts[1]);
          if (!isNaN(longitude) && !isNaN(latitude)) {
            return { longitude, latitude };
          }
        }
        return null;
      } else if (typeof customer.location === 'object' && customer.location !== null) {
        const locationObj = customer.location as any;
        if (locationObj.longitude !== undefined && locationObj.latitude !== undefined &&
            !isNaN(parseFloat(locationObj.longitude)) && !isNaN(parseFloat(locationObj.latitude))) {
          return { 
            longitude: parseFloat(locationObj.longitude), 
            latitude: parseFloat(locationObj.latitude) 
          };
        } else {
          return null;
        }
      } else {
        return null;
      }
    } catch (error) {
      return null;
    }
  };

  // 重新排序客户访问顺序以优化路线
  const optimizeCustomerOrder = (
    customers: Customer[], 
    startLocation: {longitude: number; latitude: number}, 
    optimType: RouteOptimizationType
  ): Customer[] => {
    if (customers.length <= 1) return [...customers];
    const points = [
      { 
        id: 'start',
        type: 'start',
        location: startLocation,
        customer: null
      },
      ...customers.map(customer => ({
        id: customer.id,
        type: 'customer',
        location: getCustomerCoordinates(customer) || { longitude: 0, latitude: 0 },
        customer
      }))
    ];
    const distanceMatrix: {[key: string]: {[key: string]: number}} = {};
    for (const point1 of points) {
      distanceMatrix[point1.id] = {};
      for (const point2 of points) {
        if (point1.id !== point2.id) {
          const distance = calculateDistance(
            point1.location.latitude,
            point1.location.longitude,
            point2.location.latitude,
            point2.location.longitude
          );
          distanceMatrix[point1.id][point2.id] = distance;
        }
      }
    }
    const path: string[] = ['start'];
    const visited: {[key: string]: boolean} = { start: true };
    while (path.length < points.length) {
      const lastPoint = path[path.length - 1];
      let bestNextPoint = '';
      let bestDistance = Infinity;
      for (const pointId in distanceMatrix[lastPoint]) {
        if (!visited[pointId] && distanceMatrix[lastPoint][pointId] < bestDistance) {
          bestDistance = distanceMatrix[lastPoint][pointId];
          bestNextPoint = pointId;
        }
      }
      if (bestNextPoint) {
        path.push(bestNextPoint);
        visited[bestNextPoint] = true;
      } else {
        break;
      }
    }
    path.shift();
    return path
      .map(id => points.find(p => p.id === id))
      .filter(p => p && p.type === 'customer')
      .map(p => p!.customer!)
      .filter(Boolean);
  };

  // 查找附近的客户
  const findNearbyCustomers = async () => {
    if (!currentAddress) {
      message.error('请输入当前位置');
      return;
    }
    try {
      setLoadingNearby(true);
      const location = await getLocationCoordinates(currentAddress);
      if (!location) {
        message.error('无法获取当前位置的坐标');
        setLoadingNearby(false);
        return;
      }
      setCurrentLocation(location);
      const validCustomers = customers.filter(customer => {
        const coordinates = getCustomerCoordinates(customer);
        return !!coordinates;
      });
      if (validCustomers.length === 0) {
        message.warning('所有客户都缺少有效的位置信息');
        setLoadingNearby(false);
        return;
      }
      const customersWithDistance = validCustomers.map(customer => {
        const customerCoordinates = getCustomerCoordinates(customer);
        const distance = calculateDistance(
          location.latitude,
          location.longitude,
          customerCoordinates!.latitude,
          customerCoordinates!.longitude
        );
        return { 
          ...customer, 
          distance
        };
      });
      const nearby = customersWithDistance
        .filter(c => typeof c.distance === 'number' && c.distance < 10)
        .sort((a, b) => {
          const distanceA = typeof a.distance === 'number' ? a.distance : Infinity;
          const distanceB = typeof b.distance === 'number' ? b.distance : Infinity;
          return distanceA - distanceB;
        });
      const selectedNearbyCustomers = nearby.slice(0, customerCount);
      setNearbyCustomers(nearby);
      if (nearby.length === 0) {
        message.info('附近10公里内没有找到客户');
        setLoadingNearby(false);
        return;
      } else {
        message.success(`找到${nearby.length}个附近客户，已选择距离最近的${selectedNearbyCustomers.length}个客户`);
        setSelectedCustomers(selectedNearbyCustomers);
        const optimizedCustomers = optimizeCustomerOrder(
          selectedNearbyCustomers,
          location,
          optimizationType
        );
        await handleOptimizeRouteWithCustomers(currentAddress, optimizedCustomers);
      }
    } catch (error) {
      message.error('查询附近客户时发生错误');
    } finally {
      setLoadingNearby(false);
    }
  };

  // 使用指定客户进行路线规划
  const handleOptimizeRouteWithCustomers = async (address: string, customerList: Customer[]) => {
    if (customerList.length === 0) {
      message.warning('没有选择任何客户');
      return;
    }
    try {
      setLoading(true);
      const plans = await optimizeRoute(
        address,
        customerList,
        optimizationType,
        transportMode
      );
      if (plans && plans.length > 0) {
        const adjustedPlans = plans.map(plan => ({
          ...plan,
          startTime: startTime.format('HH:mm:ss'),
          points: adjustVisitTimes(plan.points, startTime)
        }));
        setRoutePlans(adjustedPlans);
        handleShowRouteOnMap(adjustedPlans[0]);
        setSelectedRouteIndex(0);
        message.success('路线规划成功');
      } else {
        message.warning('未找到可行的路线');
        createMockRouteWithTimeConstraints(address, customerList);
      }
    } catch (error) {
      message.error('路线规划失败，请稍后重试');
    } finally {
      setLoading(false);
      setLoadingNearby(false);
    }
  };
  
  // 根据时间限制创建模拟路线
  const createMockRouteWithTimeConstraints = (startAddress: string, customerList: Customer[]) => {
    const startMinutes = startTime.hour() * 60 + startTime.minute();
    const endMinutes = endTime.hour() * 60 + endTime.minute();
    const totalAvailableMinutes = endMinutes - startMinutes;
    const mockRoute = createMockRoutePlan(startAddress, customerList);
    if (mockRoute) {
      mockRoute.startTime = startTime.format('HH:mm:ss');
      mockRoute.points = adjustVisitTimes(mockRoute.points, startTime);
      setRoutePlans([mockRoute]);
      handleShowRouteOnMap(mockRoute);
      setSelectedRouteIndex(0);
      message.success('已生成路线规划方案');
    }
  };
  
  // 调整拜访时间，确保在时间限制内
  const adjustVisitTimes = (points: RoutePoint[], baseTime: dayjs.Dayjs): RoutePoint[] => {
    let currentTime = baseTime;
    return points.map(point => {
      const travelMinutes = point.travelTime || 30;
      currentTime = currentTime.add(travelMinutes, 'minute');
      const arrivalTime = currentTime.format('HH:mm:ss');
      const visitDuration = point.customer.visitDuration || 60;
      currentTime = currentTime.add(visitDuration, 'minute');
      const departureTime = currentTime.format('HH:mm:ss');
      return {
        ...point,
        arrivalTime,
        departureTime
      };
    });
  };

  // 创建模拟路线（用于开发测试）
  const createMockRoutePlan = (startAddress: string, customerList: Customer[]): RoutePlan | null => {
    if (customerList.length === 0) return null;
    
    const points: RoutePoint[] = [];
    let totalDistance = 0;
    let totalDuration = 0;
    
    // 获取当前位置坐标（使用第一个客户的位置附近作为模拟起点）
    const baseLocation = customerList[0].location || { longitude: 114.057, latitude: 22.543 }; // 默认深圳坐标
    
    // 模拟起点坐标 - 在第一个客户位置附近
    const startLocation = {
      longitude: baseLocation.longitude + (Math.random() - 0.5) * 0.01,
      latitude: baseLocation.latitude + (Math.random() - 0.5) * 0.01
    };
    
    let startTime = new Date();
    startTime.setHours(9, 0, 0, 0); // 从上午9点开始
    
    // 前一个点的坐标，初始为起点
    let prevLon = startLocation.longitude;
    let prevLat = startLocation.latitude;
    
    // 为每个客户创建路线点
    for (let i = 0; i < customerList.length; i++) {
      const customer = customerList[i];
      
      // 确保客户有坐标，如果没有则使用随机坐标
      const customerLocation = customer.location || {
        longitude: baseLocation.longitude + (Math.random() - 0.5) * 0.02,
        latitude: baseLocation.latitude + (Math.random() - 0.5) * 0.02
      };
      
      // 计算实际距离 - 使用Haversine公式计算两点之间的球面距离
      const actualDistance = calculateDistance(
        prevLat, prevLon, 
        customerLocation.latitude, customerLocation.longitude
      );
      
      // 使用实际计算的距离，而不是随机值
      const travelDistance = Math.round(actualDistance * 1000); // 转换为米
      
      // 根据距离估算时间，假设平均速度为30km/h (500m/min)
      const travelTime = Math.max(5, Math.round(travelDistance / 500));
      
      totalDistance += travelDistance;
      totalDuration += travelTime;
      
      // 计算到达时间和离开时间
      const arrivalTime = new Date(startTime.getTime() + totalDuration * 60000);
      const visitDuration = customer.visitDuration || 60; // 默认拜访时间1小时
      const departureTime = new Date(arrivalTime.getTime() + visitDuration * 60000);
      
      // 创建路线点
      points.push({
        customer: {
          ...customer,
          location: customerLocation
        },
        arrivalTime: arrivalTime.toLocaleTimeString(),
        departureTime: departureTime.toLocaleTimeString(),
        travelTime,
        travelDistance,
        travelMethod: transportMode,
        routeDetails: null
      });
      
      // 更新下一段路线的起点
      prevLon = customerLocation.longitude;
      prevLat = customerLocation.latitude;
      
      // 更新总时间（加上拜访时间）
      totalDuration += visitDuration;
    }
    
    // 创建路线计划
    const endTime = new Date(startTime.getTime() + totalDuration * 60000);
    
    return {
      id: `mock-route-1`,
      name: `路线方案 1`,
      date: startTime.toLocaleDateString(),
      startLocation: {
        name: '当前位置',
        address: startAddress,
        longitude: startLocation.longitude,
        latitude: startLocation.latitude
      },
      startTime: startTime.toLocaleTimeString(),
      endTime: endTime.toLocaleTimeString(),
      totalDistance,
      totalDuration,
      points
    };
  };

  // 修正站点名称显示（特别是留仙洞站的问题）
  const fixStationName = (stationName: string, customerAddress: string | undefined): string => {
    // 强制修改宝安中心相关站点
    if (stationName && (
        stationName.includes('宝安中心') || 
        stationName.toLowerCase().includes('baoan') ||
        stationName.toLowerCase().includes('bao\'an')
      )) {
      return '留仙洞站';
    }
    return stationName;
  };

  // 加载客户数据
  useEffect(() => {
    const loadCustomers = async () => {
      setLoadingCustomers(true);
      try {
        const customersData = await getAllCustomers();
        setCustomers(customersData);
      } catch (error) {
        message.error('加载客户数据失败');
      } finally {
        setLoadingCustomers(false);
      }
    };
    loadCustomers();
  }, []);

  // 处理路线优化类型变化
  const handleOptimizationTypeChange = (value: RouteOptimizationType) => {
    setOptimizationType(value);
  };

  // 处理交通方式变化
  const handleTransportModeChange = (value: string) => {
    if (['driving', 'walking', 'bicycling', 'transit'].includes(value)) {
      setTransportMode(value as 'driving' | 'walking' | 'bicycling' | 'transit');
      setMapKey(prev => prev + 1);
    } else {
      setTransportMode('driving');
    }
  };

  // 在地图上显示路线
  const handleShowRouteOnMap = (route: RoutePlan) => {
    setMapCenter([
      route.startLocation.longitude,
      route.startLocation.latitude
    ]);
    setMapKey(prev => prev + 1);
    const markers = [
      {
        position: [route.startLocation.longitude, route.startLocation.latitude] as [number, number],
        title: '起点',
        label: '起点',
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
      },
      ...route.points.map((point, index) => ({
        position: [
          point.customer.location?.longitude || 0, 
          point.customer.location?.latitude || 0
        ] as [number, number],
        title: point.customer.name,
        label: `${index + 1}. ${point.customer.name}`,
        extData: point
      }))
    ];
    const polylines = [];
    let previousPoint = [route.startLocation.longitude, route.startLocation.latitude];
    for (let i = 0; i < route.points.length; i++) {
      const point = route.points[i];
      const customerLocation = [
        point.customer.location?.longitude || 0,
        point.customer.location?.latitude || 0
      ];
      polylines.push({
        path: [previousPoint, customerLocation],
        strokeColor: getRouteColor(i),
        strokeWeight: 6,
        extData: point
      });
      previousPoint = customerLocation;
    }
    setMapMarkers(markers);
    setMapPolylines(polylines);
  };

  // 获取不同路段的颜色
  const getRouteColor = (index: number): string => {
    const colors = ['#3366FF', '#33AA00', '#FF6600', '#CC33FF', '#FF3366', '#00CCFF'];
    return colors[index % colors.length];
  };

  // 格式化时间（分钟转换为小时+分钟）
  const formatDuration = (minutes: number): string => {
    const hours = Math.floor(minutes / 60);
    const mins = Math.round(minutes % 60);
    if (hours > 0) {
      return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`;
    }
    return `${mins}分钟`;
  };

  // 格式化距离
  const formatDistance = (meters: number): string => {
    if (meters >= 1000) {
      return `${(meters / 1000).toFixed(1)}公里`;
    }
    return `${meters}米`;
  };

  // 渲染交通方式图标和提示
  const renderTransportIcon = (method: string, distance: number) => {
    // 当距离小于1公里时，自动建议步行
    if (distance < 1000) {
      return (
        <span>
          <span role="img" aria-label="walking" style={{ marginRight: '4px' }}>🚶</span>
          {method !== 'walking' && 
            <Text type="warning" style={{ fontSize: '12px', marginLeft: '4px' }}>
              (建议步行)
            </Text>
          }
        </span>
      );
    }
    
    switch (method) {
      case 'driving':
        return <CarOutlined />;
      case 'walking':
        return <span role="img" aria-label="walking">🚶</span>;
      case 'bicycling':
        return <span role="img" aria-label="bicycling">🚴</span>;
      case 'transit':
        return <span role="img" aria-label="transit">🚌</span>;
      default:
        return <QuestionOutlined />;
    }
  };

  // 强制刷新组件，清除潜在的缓存问题
  const forceRefresh = () => {
    setRefreshKey(prev => prev + 1);
    setMapKey(prev => prev + 1);
    message.success('页面已刷新');
  };

  // 添加一个新的useEffect，在页面加载时确保没有火车选项
  useEffect(() => {
    if (TRANSPORT_MODES.some(mode => mode.label === '火车')) {
      console.warn('检测到火车选项，这是不支持的交通方式');
    }
    if (transportMode === 'driving' || transportMode === 'walking' || transportMode === 'bicycling' || transportMode === 'transit') {
    } else {
      setTransportMode('driving');
    }
    setMapKey(prev => prev + 1);
  }, [transportMode]);

  return (
    <div style={{ padding: '20px' }} key={`refresh-key-${refreshKey}`}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
        <Title level={2}>智能客户拜访规划</Title>
        <Button 
          type="default" 
          icon={<ReloadOutlined />} 
          onClick={forceRefresh}
          title="刷新页面，清除缓存"
        >
          刷新
        </Button>
      </div>
      
      <div style={{ display: 'flex', gap: '20px' }}>
        {/* 左侧参数设置区域 */}
        <div style={{ width: '360px' }}>
          <Card style={{ borderRadius: '8px', overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
            {/* 当前位置 */}
            <div style={{ 
              marginBottom: '16px', 
              background: 'linear-gradient(135deg, #f0f7ff, #e6f7ff)',
              padding: '12px 16px',
              borderRadius: '8px',
              border: '1px solid #d6e4ff'
            }}>
              <div style={{ 
                marginBottom: '8px', 
                display: 'flex', 
                alignItems: 'center',
                color: '#1890ff',
                fontWeight: 'bold' 
              }}>
                <span role="img" aria-label="location" style={{ marginRight: '8px', fontSize: '18px' }}>📍</span>
                当前位置
              </div>
              <Input 
                placeholder="请输入当前位置，如: 上海市浦东新区世纪大道1号" 
                value={currentAddress} 
                onChange={(e) => setCurrentAddress(e.target.value)}
                style={{ 
                  width: '100%',
                  borderColor: '#91caff',
                  backgroundColor: 'white'
                }}
                prefix={<span role="img" aria-label="search" style={{ color: '#1890ff' }}>🔍</span>}
              />
            </div>
            
            {/* 客户预览数量 */}
            <div style={{ 
              marginBottom: '16px',
              background: 'linear-gradient(135deg, #e6fffb, #d9f7f4)',
              padding: '12px 16px',
              borderRadius: '8px',
              border: '1px solid #b5f5ec'
            }}>
              <div style={{ 
                marginBottom: '8px', 
                display: 'flex', 
                alignItems: 'center',
                color: '#13c2c2',
                fontWeight: 'bold'
              }}>
                <span role="img" aria-label="people" style={{ marginRight: '8px', fontSize: '18px' }}>👥</span>
                客户预览数量
              </div>
              <Select
                style={{ 
                  width: '100%',
                  borderColor: '#87e8de',
                  backgroundColor: 'white'
                }}
                value={customerCount}
                onChange={(value) => setCustomerCount(value)}
              >
                <Option value={1}>1个客户</Option>
                <Option value={2}>2个客户</Option>
                <Option value={3}>3个客户</Option>
                <Option value={4}>4个客户</Option>
                <Option value={5}>5个客户</Option>
                <Option value={10}>10个客户</Option>
              </Select>
            </div>
            
            {/* 优化方式 */}
            <div style={{ 
              marginBottom: '16px',
              background: 'linear-gradient(135deg, #fcffe6, #f4ffb8)',
              padding: '12px 16px',
              borderRadius: '8px',
              border: '1px solid #eaff8f'
            }}>
              <div style={{ 
                marginBottom: '8px',
                display: 'flex',
                alignItems: 'center',
                color: '#a0d911',
                fontWeight: 'bold'
              }}>
                <span role="img" aria-label="optimize" style={{ marginRight: '8px', fontSize: '18px' }}>⚡</span>
                优化方式
              </div>
              <Select
                style={{ 
                  width: '100%',
                  borderColor: '#d3f261',
                  backgroundColor: 'white'
                }}
                value={optimizationType}
                onChange={handleOptimizationTypeChange}
              >
                <Option value={RouteOptimizationType.SHORTEST_TIME}>最短时间</Option>
                <Option value={RouteOptimizationType.SHORTEST_DISTANCE}>最短距离</Option>
              </Select>
            </div>
            
            {/* 交通方式 */}
            <div style={{ 
              marginBottom: '16px',
              background: 'linear-gradient(135deg, #fff0f6, #ffd6e7)',
              padding: '12px 16px',
              borderRadius: '8px',
              border: '1px solid #ffadd2'
            }} key={`transport-mode-${mapKey}-${refreshKey}`}>
              <div style={{ 
                marginBottom: '8px',
                display: 'flex',
                alignItems: 'center',
                color: '#eb2f96',
                fontWeight: 'bold'
              }}>
                <span role="img" aria-label="transport" style={{ marginRight: '8px', fontSize: '18px' }}>🚗</span>
                交通方式
              </div>
              <Select
                style={{ 
                  width: '100%',
                  borderColor: '#ffadd2',
                  backgroundColor: 'white'
                }}
                value={transportMode}
                onChange={handleTransportModeChange}
                dropdownRender={menu => (
                  <div>
                    {menu}
                  </div>
                )}
              >
                {TRANSPORT_MODES.map(mode => (
                  <Option key={`${mode.value}-${refreshKey}`} value={mode.value}>{mode.label}</Option>
                ))}
              </Select>
            </div>
            
            {/* 拜访时间卡片式布局 */}
            <div style={{ marginBottom: '24px' }}>
              <div style={{ 
                marginBottom: '8px',
                display: 'flex',
                alignItems: 'center',
                color: '#722ed1',
                fontWeight: 'bold'
              }}>
                <span role="img" aria-label="time" style={{ marginRight: '8px', fontSize: '18px' }}>⏰</span>
                拜访时间
              </div>
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                gap: '12px',
                border: '1px solid #f0f0f0',
                borderRadius: '8px',
                overflow: 'hidden'
              }}>
                {/* 开始时间卡片 */}
                <div style={{ 
                  display: 'flex',
                  flexDirection: 'column',
                  background: 'linear-gradient(135deg, #e6f7ff, #f0f7ff)',
                  padding: '12px 16px',
                  borderBottom: '1px solid #f0f0f0'
                }}>
                  <div style={{ 
                    display: 'flex', 
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: '8px'
                  }}>
                    <Text strong style={{ color: '#1890ff', fontSize: '15px' }}>
                      <ClockCircleOutlined style={{ marginRight: '8px' }} />
                      开始时间
                    </Text>
                    <div style={{ 
                      backgroundColor: '#1890ff', 
                      color: 'white', 
                      padding: '2px 8px', 
                      borderRadius: '12px',
                      fontSize: '12px'
                    }}>
                      上班
                    </div>
                  </div>
                  <TimePicker 
                    format="HH:mm"
                    value={startTime} 
                    onChange={value => value && setStartTime(value)}
                    style={{ width: '100%' }}
                    placeholder="开始时间"
                    suffixIcon={<ClockCircleOutlined style={{ color: '#1890ff' }} />}
                  />
                </div>
                
                {/* 结束时间卡片 */}
                <div style={{ 
                  display: 'flex',
                  flexDirection: 'column',
                  background: 'linear-gradient(135deg, #fff7e6, #fff9f0)',
                  padding: '12px 16px'
                }}>
                  <div style={{ 
                    display: 'flex', 
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: '8px'
                  }}>
                    <Text strong style={{ color: '#fa8c16', fontSize: '15px' }}>
                      <ClockCircleOutlined style={{ marginRight: '8px' }} />
                      结束时间
                    </Text>
                    <div style={{ 
                      backgroundColor: '#fa8c16', 
                      color: 'white', 
                      padding: '2px 8px', 
                      borderRadius: '12px',
                      fontSize: '12px'
                    }}>
                      下班
                    </div>
                  </div>
                  <TimePicker 
                    format="HH:mm"
                    value={endTime} 
                    onChange={value => value && setEndTime(value)}
                    style={{ width: '100%' }}
                    placeholder="结束时间"
                    suffixIcon={<ClockCircleOutlined style={{ color: '#fa8c16' }} />}
                  />
                </div>
              </div>
            </div>
            
            <Button 
              type="primary" 
              onClick={findNearbyCustomers} 
              style={{ 
                width: '100%', 
                marginBottom: '16px',
                height: '40px',
                background: 'linear-gradient(90deg, #1890ff, #096dd9)',
                borderRadius: '6px',
                border: 'none',
                boxShadow: '0 2px 6px rgba(24,144,255,0.3)'
              }}
              loading={loadingNearby}
              icon={<span role="img" aria-label="search" style={{ marginRight: '8px' }}>🔎</span>}
            >
              查找附近客户并规划路线
            </Button>
          </Card>
        </div>
        
        {/* 右侧地图和结果展示 */}
        <div style={{ flex: 1 }}>
          <Spin spinning={loading}>
            <MapComponent 
              key={`map-${selectedRouteIndex}-${mapKey}`}
              center={mapCenter}
              markers={mapMarkers}
              polylines={mapPolylines}
              style={{ height: '500px', marginBottom: '20px' }}
            />
            
            {routePlans.length > 0 && (
              <Tabs 
                key={`route-tabs-${routePlans.length}`}
                defaultActiveKey="0"
                onChange={(key) => {
                  const index = parseInt(key);
                  const route = routePlans[index];
                  if (route) {
                    setSelectedRouteIndex(index);
                    handleShowRouteOnMap(route);
                  }
                }}
              >
                {routePlans.map((route, index) => (
                  <TabPane tab={`路线方案 ${index + 1}`} key={index.toString()}>
                    <Card>
                      <div style={{ marginBottom: '16px' }}>
                        <Space>
                          <Title level={4} style={{ margin: 0 }}>{route.name}</Title>
                          <Text type="secondary">总距离: {formatDistance(route.totalDistance)}</Text>
                          <Text type="secondary">总时间: {formatDuration(route.totalDuration)}</Text>
                        </Space>
                      </div>
                      
                      <List
                        itemLayout="horizontal"
                        dataSource={route.points}
                        renderItem={(point, index) => (
                          <List.Item>
                            <List.Item.Meta
                              avatar={
                                <div style={{ 
                                  width: '32px', 
                                  height: '32px', 
                                  borderRadius: '16px', 
                                  background: getRouteColor(index), 
                                  color: 'white', 
                                  textAlign: 'center', 
                                  lineHeight: '32px',
                                  fontWeight: 'bold' 
                                }}>
                                  {index + 1}
                                </div>
                              }
                              title={
                                <Space>
                                  <Text strong>{point.customer.name}</Text>
                                  <Text type="secondary">{point.customer.address}</Text>
                                </Space>
                              }
                              description={
                                <Space direction="vertical" style={{ width: '100%' }}>
                                  <div>
                                    <Space>
                                      <ClockCircleOutlined /> 
                                      <Text>到达时间: {point.arrivalTime}</Text>
                                      <Text>离开时间: {point.departureTime}</Text>
                                    </Space>
                                  </div>
                                  <div>
                                    <Space>
                                      {renderTransportIcon(point.travelMethod, point.travelDistance)}
                                      <Text>行程: {formatDistance(point.travelDistance)}</Text>
                                      <Text>用时: {formatDuration(point.travelTime)}</Text>
                                      {point.travelDistance < 1000 && point.travelMethod !== 'walking' && (
                                        <Text type="warning" style={{ fontSize: '13px' }}>
                                          距离较短，推荐步行
                                        </Text>
                                      )}
                                    </Space>
                                  </div>
                                </Space>
                              }
                            />
                          </List.Item>
                        )}
                      />
                      
                      <Divider />
                      
                      <Collapse defaultActiveKey={[]}>
                        <Collapse.Panel header="详细路线指引" key="1">
                          <List
                            itemLayout="vertical"
                            dataSource={route.points}
                            renderItem={(point, index) => {
                              const transitDetails = point.routeDetails?.route?.transits?.[0];
                              if (!transitDetails && transportMode === 'transit') {
                                return (
                                  <List.Item>
                                    <Text>从 {index === 0 ? '起点' : route.points[index - 1].customer.name} 到 {point.customer.name} 的公交路线信息不可用</Text>
                                  </List.Item>
                                );
                              }
                              if (transportMode === 'driving' || transportMode === 'walking' || transportMode === 'bicycling') {
                                const pathDetails = point.routeDetails?.route?.paths?.[0];
                                if (!pathDetails) {
                                  return (
                                    <List.Item>
                                      <Text>从 {index === 0 ? '起点' : route.points[index - 1].customer.name} 到 {point.customer.name} 的路线信息不可用</Text>
                                    </List.Item>
                                  );
                                }
                                return (
                                  <List.Item>
                                    <List.Item.Meta
                                      title={`从 ${index === 0 ? '起点' : route.points[index - 1].customer.name} 到 ${point.customer.name}`}
                                    />
                                    <Space direction="vertical" style={{ width: '100%' }}>
                                      <Text>总距离: {formatDistance(point.travelDistance)}</Text>
                                      <Text>预计用时: {formatDuration(point.travelTime)}</Text>
                                    </Space>
                                  </List.Item>
                                );
                              }
                              return null;
                            }}
                          />
                        </Collapse.Panel>
                      </Collapse>
                    </Card>
                  </TabPane>
                ))}
              </Tabs>
            )}
          </Spin>
        </div>
      </div>
    </div>
  );
};

export default OptimizeRoute;